//
//  UIImageUtils.swift
//  Reader17kSDK
//
//  Created by 朴社长 on 2020/11/5.
//

import Foundation
import UIKit

public extension UIImage {
    
    func withColor(_ color: UIColor? = nil) -> UIImage {
        imageWith(color: color ?? UIColor.clear)
    }
    
    func imageWith(color: UIColor) -> UIImage {
        UIGraphicsBeginImageContextWithOptions(size, false, scale)
        let context = UIGraphicsGetCurrentContext()
        context?.translateBy(x: 0, y: size.height)
        context?.scaleBy(x: 1.0, y: -1.0)
        context?.setBlendMode(.normal)
        let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
        context?.clip(to: rect, mask: cgImage!);
        color.setFill()
        context?.fill(rect)
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return newImage ?? UIImage()
    }
    
    class func image(color: UIColor, size: CGSize = CGSize(width: 44, height: 44)) -> UIImage {
        let rect = CGRect(origin: CGPoint.zero, size: size)
        let renderer = UIGraphicsImageRenderer(size: size)
        
        let image = renderer.image { ctx in
            color.setFill()
            ctx.fill(rect)
        }
        
        return image
    }

    
    class func gradientImage(colors:[UIColor], startPoint: CGPoint = CGPoint(x: 0.0, y: 0.5), endPoint:CGPoint = CGPoint(x: 1.0, y: 0.5), frame:CGRect = CGRect(origin: .zero, size: CGSize(width: 44, height: 44))) -> UIImage? {
        let gradientLayer = CAGradientLayer()
        gradientLayer.colors = colors.map({ $0.cgColor})
        gradientLayer.startPoint = startPoint
        gradientLayer.endPoint = endPoint
        gradientLayer.frame = frame

        let renderer = UIGraphicsImageRenderer(size: gradientLayer.bounds.size)
        let image = renderer.image { ctx in
            gradientLayer.render(in: ctx.cgContext)
        }
        return image
    }
}

public extension UIImage {
    func resized(to newSize: CGSize) -> UIImage? {
        UIGraphicsBeginImageContextWithOptions(newSize, false, UIScreen.main.scale)
        defer { UIGraphicsEndImageContext() }
        
        self.draw(in: CGRect(origin: .zero, size: newSize))
        return UIGraphicsGetImageFromCurrentImageContext()
    }
}
